using UnityEngine;
using System.Collections.Generic;

public class GameScript : MonoBehaviour {
    
	//ELEVATOR
    public GameObject elevator;
	
	//BACKGROUND
	public GameObject bg;
	private static List<GameObject> bgList;
	
	//ENEMY
	public GameObject enemy;
    private float rand;//random track for enemies
    private List<GameObject> enemyList;
    private GameObject enemyInstance;
    public float enemySpacingMultiplier; //spacing betwween them
    
	//COIN
	public GameObject coin;
	private List<GameObject> coinList;

    //GAME VARIABLES
    private float updateTimer;
    private float updateClock;
    private Touch touch;

    //SCORE
    public GUIText scoreText;
    private float scoreTimer;
    private float scoreClock;
    public static int score;

    // Use this for initialization
    void Start()
    {
		//GAME VARIABLES
        updateTimer = 0.024f;//the less the faster
		loadGameVariables();
		//SCORE
        scoreTimer = 0.16f;//the less the faster
		//BACKGROUND
		MainScript.bgShiftYInitial = 10.0f;
		MainScript.bgCount = 3;
		GameObject bgInstance;
		bgList = new List<GameObject>();
		for (int i = 0; i < MainScript.bgCount; i++) {
			if (i == 0) {
				bg.name = "bgInstance0";
				bg.transform.localScale = scaleToScreen(bg);
				//piece on the top, first one to appear
				bgList.Add(bg);
			}
			else {
				bgInstance = (GameObject)Instantiate(bg);
				bgInstance.transform.localScale = scaleToScreen(bgInstance);
				bgInstance.transform.position = Vector3.up * (-bgInstance.transform.collider.bounds.size.y*i);
				bgInstance.name = "bgInstance" + i;
				//from the second piece to the last one
				bgList.Add(bgInstance);
			}
		}
		//ENEMY
		MainScript.enemySize = new Vector2(24.0f, 24.0f);
		MainScript.enemyCount = 10;
		MainScript.enemySpacing = 4;
		MainScript.enemySpacingRangomRange = 2;
		enemyList = new List<GameObject>();
		enemyGenerator();
		
    }
	
	void enemyGenerator(){
	
        enemySpacingMultiplier = elevator.GetComponent<ElevatorScript>().tracksSpacingPercentage;
        
        for (int i = 0; i < MainScript.enemyCount; i++)
        {
            rand = 0;//(((int)Random.Range(-1, 2)) * enemy.transform.collider.bounds.size.x)+MainScript.scaleFromScreen(enemySpacingMultiplier);
            enemyInstance = (GameObject)Instantiate(enemy);
            enemyInstance.transform.position = new Vector3(rand,
				bgList[bgList.Count-1].transform.position.y-((enemyInstance.collider.bounds.size.y/2.0f)*(i))-
				Random.Range(MainScript.enemySpacing-MainScript.enemySpacingRangomRange, MainScript.enemySpacing + MainScript.enemySpacingRangomRange),
				elevator.transform.position.z);
            enemyInstance.name = "enemyInstance" + i;
			enemyInstance.transform.localScale = scaleToScreen(enemyInstance, MainScript.enemySize.x, MainScript.enemySize.y);
            enemyList.Add(enemyInstance);
        }
	}
	
	public static void updateEnemyList(){
			
	}
	
	/// <summary>
	/// Called when BgScript makes a piece go down (after turning not visible anymore)
	/// Update the Background List
	/// </summary>
	public static void updateBgList(){
		//Do something to the new last piece
		// inverte cor
		bgList[0].renderer.material.color = new Color(1-bgList[0].renderer.material.color.r,
			1-bgList[0].renderer.material.color.g,1-bgList[0].renderer.material.color.b,
			bgList[0].renderer.material.color.a);
		//faz balada (do mário)	
		/*bgList[0].renderer.material.color = new Color(Random.value,
			Random.value,Random.value,
			Random.value);*/
		
		//bgList[0].renderer.sharedMaterial.shader = 
		//Place the new last piece on the last position of the list
		bgList.Add(bgList[0]);
		bgList.RemoveAt(0);
		bgList.TrimExcess();
	}
	
	//Called on Start method on this class
	public static void loadGameVariables(){
		MainScript.cameraSize = Camera.main.orthographicSize;//7.5f
	}
	
	/// <summary>
	/// Get a GameObject and return its transform.localScale already scaled to the 100% of the screen
	/// </summary>
	/// <param name='objectToScale'>
	/// GameObject to scale. (ex.: background)
	/// </param>
	private Vector3 scaleToScreen(GameObject objectToScale){
		Vector3 outputSize = objectToScale.collider.bounds.size;//assign Z size (constant)
		float aspectRatio = MainScript.cameraSize / ((float)Screen.height / (float)Screen.width);
		outputSize.y= MainScript.cameraSize/aspectRatio;// * 2.0f;
		outputSize.x= outputSize.y* ((float)Screen.width / (float)Screen.height);
		return outputSize;
	}
	
	private Vector3 scaleToScreen(GameObject objectToScale, float _height, float _width){
		Vector3 outputSize = objectToScale.collider.bounds.size;//assign Z size (constant)
		float aspectRatio = MainScript.cameraSize / ((float)Screen.height / (float)Screen.width);
		outputSize.y= MainScript.cameraSize/aspectRatio;// * 2.0f;
		outputSize.x= outputSize.y* ((float)Screen.width / (float)Screen.height);
		
		outputSize.y *= _height/100.0f;
		outputSize.x *= _width/100.0f;
		return outputSize;
	}
	
    public static void gameOver(){
        
        //MainScript.SaveGame();
        PlayerPrefs.SetInt("score", score);
        if (score > PlayerPrefs.GetInt("highScore"))
        {
            PlayerPrefs.SetInt("highScore", score);
        }
        score = 0;
        //play animation, cloud growing
        Application.LoadLevel("gameOver");

    }

    // Update is called once per frame
    void Update()
    {
        //back to menu - Escape on Android is the smartphone back button
        if (Input.GetKeyDown(KeyCode.Escape)) Application.LoadLevel("menu");
        
        updateClock += Time.deltaTime;
        if (updateClock > updateTimer)
        {
            scoreClock += Time.deltaTime;
            if (scoreClock > scoreTimer)
            {
                score++;
                scoreClock = 0;
            }
            updateClock = 0.0f;
            scoreText.text = "SCORE: " + score.ToString();
        }
    }
}